package org.apache.jmeter.extractor.json.jsonpath;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * @author 0801771X0
 *
 */

public class JsonResponseUtil {
	
	
	private static final Logger log = LoggerFactory.getLogger(JsonResponseUtil.class);
	/**
	 * 根据关键查找包含关键字的 json 串
	 * @param responseStr
	 * @param keyStr
	 * @return
	 */
	public String getResponseByKey(String responseStr, String keyStr){
//		log.info("responseStr: " + responseStr);
		log.info("keyStr: " + keyStr);
		String[] strArray = responseStr.split("\\n");
		for (String str : strArray) {
//			log.info("str: " + str);
			JSONObject responseJsonObject = JSONObject.parseObject(str);
			String responseKeyStr = responseJsonObject.toString();
			if(responseKeyStr.contains(keyStr)){
				return responseKeyStr;
			}
		}
		return "not found response by keyStr[" + keyStr + "]";
	}
	
	/**
	 * 计算字符串中出现字符的次数
	 * @param srcStr 字符串
	 * @param distStr 字符串
	 * @return
	 */
	public int countChar(String srcStr, String distStr){
		int count = 0;
		Pattern pattern = Pattern.compile(distStr);
		Matcher matcher = pattern.matcher(srcStr);
		while (matcher.find()) {
			count++;
		}
		return count;
	}
	
}
